<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // flat 拍平 指定层数
      // Infinity
      console.log([1, 2, [2, 3, [4, 5]]].flat(Infinity));

      // es5 递归实现
      function flatten(arr) {
        var res = [];
        for (var i = 0; i < arr.length; i++) {
          if (Array.isArray(arr[i])) {
            res = res.concat(flatten(arr[i]));
          } else {
            res.push(arr[i]);
          }
        }
        return res;
      }
      console.log(flatten([1, 2, [2, 3, [4, 5]]]));

      // es6实现
      console.log([].concat(...[1, 2, [2, 3, [4, 5]]])); // 序列 1 2 [2, 3, Array(2)]
      // [1, 2, 2, 3, Array(2)]
      function flatten2(arr) {
        while (arr.some((item) => Array.isArray(item))) {
          arr = [].concat(...arr);
        }
      }
    </script>
  </body>
</html>
